package com.bootdo.wx.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.config.WxMaConfiguration;
import com.bootdo.common.config.WxMaProperties;
import com.bootdo.common.utils.*;
import com.bootdo.wx.domain.*;
import com.bootdo.wx.service.*;
import com.github.pagehelper.PageInfo;
import me.chanjar.weixin.common.session.WxSessionManager;
import org.apache.commons.beanutils.BeanUtils;
import org.jsoup.Connection.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by HP on 2019/5/28.
 */

@Controller
@RequestMapping("/api/member")
public class ApiMemberController {

    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private MemberAddressService memberAddressService;
    @Autowired
    private SetWechatService setWechatService;
    @Autowired
    private MemberTokenService memberTokenService;
    @Autowired
    private MemberFeedbackService memberFeedbackService;
    @Autowired
    private MemberSignService memberSignService;
    @Autowired
    private CmsContentService cmsContentService;
    @Autowired
    private MemberScoreService memberScoreService;
    @Autowired
    private MemberSignRewardService memberSignRewardService;
    @Autowired
    private CmsSignService cmsSignService;
    @Autowired
    private SetImageUploadService setImageUploadService;
    @Autowired
    private OrderShippingService orderShippingService;




    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private WxMaProperties properties;
     //final WxMaService wxService = WxMaConfiguration.getMaService(appid);
    //wxService.getMsgService().sendSubscribeMsg(WxMaSubscribeMessage subscribeMessage); 发送订阅消息



    /**
     * 商品二维码
     */
    @PostMapping("/getGoodsQrcode")
    @ResponseBody
    public R getGoodsQrcode(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
        ){
            return R.error("参数异常");
        }
        try{

            /***
             *
             * @author long
             * 2020年11月30日下午2:08:17
             * 方法释义:发送订阅信息
             * 参数:
             *
             */

            MemberUserDO memberUserDO = memberUserService.get(MapUtil.getStr(params, "userId"));
            WxMaService wxService = WxMaConfiguration.getMaService(this.properties.getConfigs().get(0).getAppid());
            //wxService.getCodeService().getQrCode()
            File file = wxService.getQrcodeService().createWxaCodeUnlimit(memberUserDO.getCode(), "");
            //String fileName = "IMG_" + image.getWidth() + "_" + image.getHeight() + "@"+ UUID.randomUUID().toString();;
            String imagePath = new ImgUpload(setImageUploadService).upload(ImgUpload.File2byte(file),
                    file.getName());
            //Map<String,Object> map = memberUserService.getMemberCenter(params);
            return R.ok().put("data",imagePath);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 我的
     * @param params
     * @return
     */
    @PostMapping("/getMemberCenter")
    @ResponseBody
    public R getMemberCenter(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
        ){
            return R.error("参数异常");
        }
        try{
            Map<String,Object> map = memberUserService.getMemberCenter(params);
            return R.ok().put("data",map);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 足迹日期
     * @param params
     * @return
     */
    @PostMapping("/getMemberHistory")
    @ResponseBody
    public R getMemberHistory(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("month")
        ){
            return R.error("参数异常");
        }
        try{
            List<String> map = memberUserService.getMemberHistory(params);
            return R.ok().put("data",map);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

     /**
     * 设置
     * @param params
     * @return
     */
    @PostMapping("/setUp")
    @ResponseBody
    public R setUp(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")
        ){
            return R.error("参数异常");
        }
        try{
            Map<String,Object> map = memberUserService.setUp(params);
            return R.ok().put("data",map);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }




    /**
     * 今日收益/月收益
     * @param params
     * @return
     */
    @PostMapping("/todayPrice")
    @ResponseBody
    public R getTodayPrice(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || params.get("userId").toString().equals("")

        ){
            return R.error("参数异常");
        }
        try{
            Map<String,Object> map = memberUserService.getTodayPrice(params);
            return R.ok().put("data",map);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 累计收益
     * @param params
     * @return
     */
    @PostMapping("/allPrice")
    @ResponseBody
    public R getAllPrice(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")||params.get("userId").toString().equals("")
        ){
            return R.error("参数异常");
        }
        try{
            Map<String,Object> map = memberUserService.getAllPrice(params);
            return R.ok().put("data",map);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }
    /**
     * 上级收益人
     * @param params
     * @return
     */
    @PostMapping("/comUser")
    @ResponseBody
    public R getcomUser(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")||params.get("userId").toString().equals("")
            || !params.containsKey("orderId")
        ){
            return R.error("参数异常");
        }
        try{
            Map<String,Object> map = memberUserService.getcomUser(params);
            return R.ok().put("data",map);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     *
     * @Title:
     * @Description: 修改个人信息
     * @param map
     * @return R
     * @author Administrator
     * @date 2018年9月27日上午10:31:23
     */
    @RequestMapping("/editUser")
    @ResponseBody
    public R editUser(@RequestBody Map<String, Object> map) {
        if (!map.containsKey("userId") || StringUtils.isBlank(map.get("userId").toString())){
            return R.error("参数错误");
        }
        try {
        	MemberUserDO memberUserDO = memberUserService.get(map.get("userId").toString());
            BeanUtils.populate(memberUserDO, map);
            memberUserService.update(memberUserDO);
            return R.ok();
        } catch (Exception e) {
            return R.error("操作失败");
        }
    }

    /**
     * 查询个人收货地址
     */
    @PostMapping( "/address/list")
    @ResponseBody
    public R addressList(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")){
            return R.error("参数异常");
        }
        try{
            String userId = params.get("userId").toString();
            List<MemberAddressDO> list = memberAddressService.queryByUserId(params);
            return R.ok().put("data", list);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }


    /**
     * 添加收货地址
     */
    @PostMapping( "/address/add")
    @ResponseBody
    public R addressAdd(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")||!params.containsKey("province")
                ||!params.containsKey("city")||!params.containsKey("county")
                ||!params.containsKey("address")
                ||!params.containsKey("fullName")||!params.containsKey("phone")
                ||!params.containsKey("default")
                ){
            return R.error("参数异常");
        }
        try{
//			String userId = params.get("userId").toString();
            memberAddressService.add(params);
            return R.ok();
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }



    /**
     * 查看订单地址
     */
    @PostMapping( "/address/select")
    @ResponseBody
    public R addressSelect(@RequestBody Map<String, Object> params){
        if (!params.containsKey("orderId")
        ){
            return R.error("参数异常");
        }
        try{
            Map<String, Object> date = memberAddressService.selectAddress(params);
            return R.ok().put("data", date);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }


    /**
     * 修改订单地址
     */
    @PostMapping( "/address/update")
    @ResponseBody
    public R updateAddress(@RequestBody Map<String, Object> params){
        if (!params.containsKey("orderId")||!params.containsKey("receiverPhone")
                ||!params.containsKey("receiverName")||!params.containsKey("receiverProvince")
                ||!params.containsKey("receiverCity")||!params.containsKey("receiverCounty")
                ||!params.containsKey("receiverAddress")
        ){
            return R.error("参数异常");
        }
        try{
            OrderShippingDO shippingDO = orderShippingService.getByOrderId(params.get("orderId").toString());
            BeanUtils.populate(shippingDO, params);
            orderShippingService.update(shippingDO);
            return R.ok();
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 修改收货地址
     */
    @PostMapping( "/address/change")
    @ResponseBody
    public R addressChange(@RequestBody Map<String, Object> params){
        if (!params.containsKey("addressId")||!params.containsKey("province")
                ||!params.containsKey("city")||!params.containsKey("county")
                ||!params.containsKey("address")||!params.containsKey("userId")
                ||!params.containsKey("fullName")||!params.containsKey("phone")
                ||!params.containsKey("default")
                ){
            return R.error("参数异常");
        }
        try{
            memberAddressService.change(params);
            return R.ok();
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 删除收货地址
     */
    @PostMapping( "/address/remove")
    @ResponseBody
    public R addressRemove(@RequestBody Map<String, Object> params){
        if (!params.containsKey("addressId")||!params.containsKey("userId")
                ){
            return R.error("参数异常");
        }
        try{
            String userId = params.get("userId").toString();
            String addressId = params.get("addressId").toString();
            MemberAddressDO addressDO = memberAddressService.get(addressId);
            if (!userId.equals(addressDO.getUserId())){
                return R.error("收货地址异常");
            }
            memberAddressService.remove(addressId);
            return R.ok("删除成功");
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 设置默认收货地址
     */
    @PostMapping( "/address/default")
    @ResponseBody
    public R addressDefault(@RequestBody Map<String, Object> params){
        if (!params.containsKey("addressId")||!params.containsKey("userId")
                ){
            return R.error("参数异常");
        }
        try{
            return memberAddressService.toDefault(params);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 获取收货地址详情
     */
    @PostMapping( "/address/getById")
    @ResponseBody
    public R getById(@RequestBody Map<String, Object> params){
        if (!params.containsKey("addressId")||!params.containsKey("userId")
                ){
            return R.error("参数异常");
        }
        try{
            String addressId = params.get("addressId").toString();
            MemberAddressDO addressDO = memberAddressService.get(addressId);
            return R.ok().put("data", addressDO);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 获得默认收货地址
     */
    @PostMapping("/address/getDefault")
    @ResponseBody
    public R getDefault(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")||!params.containsKey("userId")
                ){
            return R.error("参数异常");
        }
        try{
            params.put("defaultValue","0");
            params.put("delFlag","0");
            List<MemberAddressDO> list = memberAddressService.list(params);
            if (list.size() != 0) {
                return R.ok().put("data",list.get(0));
            } else {
                return R.ok();
            }
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 我的团队
     */
    @PostMapping("/getMyTeam")
    @ResponseBody
    public R getMyTeam(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")){
            return R.error("参数异常");
        }
        try{
            Map<String,Object> map = memberUserService.getMyTeam(params);
            return R.ok().put("data",map);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }


    /**
     * 平台公告
     */
    @PostMapping("/getNotice")
    @ResponseBody
    public R getNotice(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")){
            return R.error("参数异常");
        }
        try{
            PageInfo<Map<String,Object>> list = memberUserService.titleList(params);
            return R.ok().put("data",list);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 平台公告详情
     */
    @PostMapping("/getNoticeDetail")
    @ResponseBody
    public R getNoticeDetail(@RequestBody Map<String, Object> params){
        if (!params.containsKey("id")){
            return R.error("参数异常");
        }
        try{
            Map<String,Object> map = memberUserService.getNoticeDetail(params);
            return R.ok().put("data",map);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }


    /**
     * 我的粉丝
     * type:1：一级粉丝，2：二级粉丝，3：所有
     */
    @PostMapping("/getMyFans")
    @ResponseBody
    public R getMyFans(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
                || !params.containsKey("type") || !params.containsKey("type")
                ){
            return R.error("参数异常");
        }
        try{
            PageInfo<Map<String,Object>> map = memberUserService.getMyFans(params);
            return R.ok().put("data",map);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 获取小程序 key
     */
    @GetMapping("/getKey")
    @ResponseBody
    public R getKey(){
        try{
            Map<String,Object> paramsMap = new HashMap<String,Object>();
            paramsMap.put("delFlag","0");
            SetWechatDO setWechatDO = setWechatService.list(paramsMap).get(0);
            return R.ok().put("data",setWechatDO);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }
    
    /***
     * 
     * @author long
     * 2020年6月15日上午10:40:15
     * 方法释义: 获取用户手机号
     * 参数: userId--用户id
     *  sessionKey-- 微信授权获得的sessionKey,跟授权登陆的要一致
     * encryptedData -- 获取手机号的加密数据
     * iv -- 获取手机号的偏移量
     */
    @RequestMapping("/user/getUserPhone")
    @ResponseBody
    public R phone(@RequestBody Map<String, Object> map) {
    	if (!map.containsKey("userId") || 
    			!map.containsKey("sessionKey")||
    			!map.containsKey("encryptedData")||
    			!map.containsKey("iv")
                ){
            return R.error("参数异常");
        }
    	 Map<String,Object> paramsMap = new HashMap<String,Object>();
         paramsMap.put("delFlag","0");
    	 SetWechatDO setWechatDO = setWechatService.list(paramsMap).get(0);
         String appid = setWechatDO.getAppId();
       /*  String appsecret = setWechatDO.getAppSecret();*/
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        /*if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }*/
     // 请求参数
       /* String params = "appid=" +  appid + "&secret=" + appsecret + "&js_code=" + map.get("code").toString() + "&grant_type="
                + "authorization_code";
        Response response = HttpUtils.get("https://api.weixin.qq.com/sns/jscode2session?" + params);
        String sr = java.net.URLDecoder.decode(response.body(), "utf-8");
        // 解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(sr);
        log.error("授权登录请求json："+json);
        // 获取会话密钥（session_key）
        String session_key = json.getString("session_key").replace(" ", "+");*/
       
        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(map.get("sessionKey").toString(), map.get("encryptedData").toString(), map.get("iv").toString());
        String phoneNumber = phoneNoInfo.getPhoneNumber();
        if("".equals(phoneNumber)||phoneNumber==null){
        	return R.ok("0").put("data", "请绑定手机号");
        }
        MemberUserDO memberUserDO = memberUserService.findByPhone(phoneNumber);
        if(memberUserDO==null){
        	//如果没有手机号
        	memberUserDO= memberUserService.get(map.get("userId").toString());
			memberUserDO.setPhone(phoneNumber);
			memberUserService.update(memberUserDO);
			return R.ok().put("data", memberUserDO);
        }/*else if(memberUserDO.getDisabled()==1){}{
        	//业务员
        	MemberUserDO memberUserDO2 = memberUserService.get(map.get("userId").toString());
        	memberUserDO2.setPhone(phoneNumber);
        	memberUserDO2.setLevel(3);
			memberUserService.update(memberUserDO2);
			memberUserService.remove(memberUserDO.getId());
        }*/
        return R.ok().put("data", memberUserDO);
       /* MemberUserDO memberUserDO = memberUserService.get(map.get("userId").toString());
       // String beanToJson = JSONUtils.beanToJson(phoneNoInfo);
        memberUserDO.setPhone(phoneNumber);
        memberUserService.update(memberUserDO);*/
        
    }

    @RequestMapping("/user/getUserInfo")
    @ResponseBody
    public R getUserInfo(@RequestBody Map<String, Object> map) {
        WxMaService wxService = WxMaConfiguration.getMaService(((WxMaProperties.Config)this.properties.getConfigs().get(0)).getAppid());

        try {
            this.log.error("开始微信授权登录：" + map.toString());
            WxMaJscode2SessionResult code1 = wxService.getUserService().getSessionInfo(map.get("code").toString());
            System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + code1.toString());
            cn.hutool.json.JSONObject userInfo1 = JSONUtil.parseObj(MapUtil.getStr(map, "userInfo"));
            new WxMaUserInfo();
            WxMaUserInfo userInfo;
            if (userInfo1 != null) {
                userInfo = (WxMaUserInfo)JSONUtil.toBean(userInfo1, WxMaUserInfo.class);
                userInfo.setOpenId(code1.getOpenid());
                userInfo.setUnionId(code1.getUnionid());
            } else {
                userInfo = wxService.getUserService().getUserInfo(code1.getSessionKey(), map.get("encryptedData").toString(), map.get("iv").toString());
            }

            System.out.println("-----------------------" + userInfo.toString());
            MemberUserDO memberUserDO = this.memberUserService.queryByOpenid(userInfo.getOpenId());
            if (memberUserDO != null) {
                Map<String, Object> stringObjectMap = BeanUtil.beanToMap(memberUserDO);
                stringObjectMap.put("sessionKey", code1.getSessionKey());
                this.log.error("微信授权登录结束，老用户：" + stringObjectMap);
                return R.ok(0, "登陆成功").put("data", stringObjectMap);
            } else {
                memberUserDO = new MemberUserDO();
                memberUserDO.setName(userInfo.getNickName());
                memberUserDO.setAvator(userInfo.getAvatarUrl());
                memberUserDO.setSex(Integer.parseInt(userInfo.getGender()));
                memberUserDO.setId(UUIDUtils.getUUID());
                memberUserDO.setWechatOpenId(userInfo.getOpenId());
                memberUserDO.setCreateAt(new Date());
               /* memberUserDO.setLatitude(map.get("latitude").toString());
                memberUserDO.setLongitude(map.get("longitude").toString());*/
                memberUserDO.setUpdateAt(new Date());
                //memberUserDO.setUnionid(userInfo.getUnionId());
                memberUserDO.setDelFlag(0);
                memberUserDO.setDisabled(0);
                memberUserDO.setFreeze(new BigDecimal("0.00"));
                memberUserDO.setMoney(new BigDecimal("0.00"));
                memberUserDO.setLevel(0);

                //如果有邀请码，设为上级
                Object fatherCode = map.get("InvitationCode");
                if (fatherCode != null && !fatherCode.toString().equals("")) {
                    System.out.println("-------------------------"+fatherCode.toString());
                    //上级用户
                    MemberUserDO fatherUser = memberUserService.getByCode(fatherCode.toString());
                    if(fatherUser==null){
                        return R.error("推荐人信息有误");
                    }else{
                        memberUserDO.setIntroUser(fatherUser.getId());
                    }
                       /* UserDO.setIntroUser(fatherUser.getId());
                        UserDO.setIndirectUser(fatherUser.getIntroUser());
                        if(fatherUser.getLevel()<4){
                        	UserDO.setLevel(fatherUser.getLevel()+1);
                        }*/

                }else{
                    memberUserDO.setIntroUser("0");
                    memberUserDO.setIndirectUser("0");
                }




                boolean T = false;

                do {
                    String stringCode = RandomUtil.randomString(8);
                    MemberUserDO byCode = this.memberUserService.getByCode(stringCode);
                    if (byCode != null) {
                        T = false;
                    } else {
                        T = true;
                        memberUserDO.setCode(stringCode);
                    }
                } while(!T);

                if (this.memberUserService.save(memberUserDO) > 0) {
                    this.log.error("微信授权登录结束，新用户：" + memberUserDO.toString());
                    Map describe = BeanUtils.describe(memberUserDO);
                    describe.put("sessionKey", code1.getSessionKey());
                    return R.ok(0, "授权成功").put("data", describe);
                } else {
                    return R.error();
                }
            }
        } catch (Exception var13) {
            var13.printStackTrace();
            return R.error();
        }

    }

    /**
     * 微信用户授权  开始获取用户信息
     * @param
     * @return
     */
    @RequestMapping("/user/getUserInfoOld")
    @ResponseBody
    public R getUserInfo(@RequestBody Map<String, Object> map, WxSessionManager sessionManager) {
        log.error("开始微信授权登录：" + map.toString());
        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("delFlag","0");
        SetWechatDO setWechatDO = setWechatService.list(paramsMap).get(0);
        String appid = setWechatDO.getAppId();
        String appsecret = setWechatDO.getAppSecret();
        try {
            //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
            //////////////// ////////////////
            // 请求参数
            String params = "appid=" +  appid + "&secret=" + appsecret + "&js_code=" + map.get("code").toString() + "&grant_type="
                    + "authorization_code";
            // 发送请求
            Response response = HttpUtils.get("https://api.weixin.qq.com/sns/jscode2session?" + params);
            String sr = java.net.URLDecoder.decode(response.body(), "utf-8");
            // 解析相应内容（转换成json对象）
            JSONObject json = JSONObject.parseObject(sr);
            log.error("授权登录请求json："+json);
            // 获取会话密钥（session_key）
            String session_key = json.getString("session_key").replace(" ", "+");
            // 用户的唯一标识（openid）
            String openid = json.getString("openid");
            //查看表里有没有这个用户
            MemberUserDO memberUserDO = memberUserService.queryByOpenid(openid);
            if(memberUserDO==null){
                ////////////////2、对encryptedData加密数据进行AES解密 ////////////////
                String decrypts = AesCbcUtil.decrypt(map.get("encryptedData").toString(), session_key,
                        map.get("iv").toString(), "UTF-8");


                if (null != decrypts && decrypts.length() > 0) {
                    JSONObject jsons = JSONObject.parseObject(decrypts);
                    System.out.println("jsons:: "+jsons.toString());
                    MemberUserDO UserDO= new MemberUserDO();
                    UserDO.setName(jsons.get("nickName").toString()); // 用户昵称
                    UserDO.setAvator(jsons.get("avatarUrl").toString()); // 用户头像
                    String gender = jsons.get("gender").toString();
                    if("2".equals(gender)){
                        UserDO.setSex(2);
                    }else {
                        UserDO.setSex(1);
                    }
                    //如果有邀请码，设为上级
                    Object fatherCode = map.get("InvitationCode");
                    if (fatherCode != null && !fatherCode.toString().equals("")) {
                    	System.out.println("-------------------------"+fatherCode.toString());
                    	//上级用户
                        MemberUserDO fatherUser = memberUserService.getByCode(fatherCode.toString());
                        if(fatherUser==null){
                        	return R.error("推荐人信息有误");
                        }else{
                        	UserDO.setIntroUser(fatherUser.getId());
                        }
                       /* UserDO.setIntroUser(fatherUser.getId());
                        UserDO.setIndirectUser(fatherUser.getIntroUser());
                        if(fatherUser.getLevel()<4){
                        	UserDO.setLevel(fatherUser.getLevel()+1);
                        }*/
                        
                    }else{
                    	UserDO.setIntroUser("0");
                    	UserDO.setIndirectUser("0");
                    }
                	
                	UserDO.setLevel(0);
                	
                    String userId = UuidUtil.get32UUID();
                    Date date = new Date();
                    UserDO.setId(userId);
                    UserDO.setWechatOpenId(openid);
                    //UserDO.setAuroraId(userId);
                    UserDO.setCreateAt(date);
                    UserDO.setUpdateAt(date);
                    UserDO.setDelFlag(0);
                    UserDO.setDisabled(0);
                    UserDO.setFreeze(new BigDecimal("0.00"));
                    UserDO.setMoney(new BigDecimal("0.00"));
                    UserDO.setScore(0);
                    UserDO.setPostType(0);
                   
                    //得到不重复的邀请码
                    boolean T = false;
                    do {
                        Map userMap = new HashMap<String,Object>();
                        int code = (int)((Math.random() * 9 + 1) * 1000000);
                        String myshareCode = String.valueOf(code);
                        userMap.put("code",myshareCode);
                        List<MemberUserDO> MemberList = memberUserService.list(userMap);
                        if(MemberList.size()>0) {
                            T = false;
                        } else {
                            T = true;
                            UserDO.setCode(myshareCode);
                        }
                    } while (!T);
                    //UserDO.setWechat("");
                    if(memberUserService.save(UserDO)>0){
                        memberUserDO = UserDO;
                        UserDO.setSessionKey(session_key);
                        log.error("微信授权登录结束，新用户："+memberUserDO.toString());
                        return R.ok().put("data", UserDO);
                    }

                } else {
                    return R.error("授权失败");
                }
            }
            log.error("微信授权登录结束，老用户："+memberUserDO.toString());
            return R.ok("登陆成功").put("data", memberUserDO);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("授权失败");
        }
    }

    /**
     * 获取token
     */
    @GetMapping("/getToken")
    @ResponseBody
    public R getToken(){
        try{
            String token = memberTokenService.getToken();
            return R.ok().put("data",token);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 我的推广
     */
    @PostMapping("/getExtension")
    @ResponseBody
    public R getExtension(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
                ){
            return R.error("参数异常");
        }
        try{
            return memberUserService.getExtension(params);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 反馈意见
     */
    @PostMapping("/feedBack")
    @ResponseBody
    public R feedBack(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
                || !params.containsKey("content") || !params.containsKey("content")
                ){
            return R.error("参数异常");
        }
        try{
            MemberFeedbackDO memberFeedbackDO = new MemberFeedbackDO();
            memberFeedbackDO.setId(UuidUtil.get32UUID());
            memberFeedbackDO.setDelFlag(0);
            memberFeedbackDO.setUserId(params.get("userId").toString());
            memberFeedbackDO.setContent(params.get("content").toString());
            memberFeedbackDO.setCreateAt(new Date());
            if (memberFeedbackService.save(memberFeedbackDO) == 1) {
                return R.ok();
            }
            return R.error();
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 修改取货方式
     * postType  0:自提，1：快递
     */
    @PostMapping("/setPostType")
    @ResponseBody
    public R setPostType(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
                || !params.containsKey("postType") || !params.containsKey("postType")
                ){
            return R.error("参数异常");
        }
        try{
            String userId = params.get("userId").toString();
            int postType = Integer.valueOf(params.get("postType").toString());
            MemberUserDO userDO = new MemberUserDO();
            userDO.setId(userId);
            userDO.setPostType(postType);
            if (memberUserService.update(userDO) == 1) {
                return R.ok();
            }
            return R.error();
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 去签到
     */
    @PostMapping("/addSign")
    @ResponseBody
    public R addSign(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
                ){
            return R.error("参数异常");
        }
        try{
            //Date date = new Date();
           // SimpleDateFormat sdf1 =new SimpleDateFormat("yyyy-MM-dd" );
          //  String str1 = sdf1.format(date);
            String userId = params.get("userId").toString();
            if (memberSignService.getTodaySign(userId).size() != 0) {
                return R.error("你今天已经签到过了");
            }
            return memberSignService.addSign(params);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 获取签到记录
     * month  需要请求的年月，比如  2019-07
     */
    @PostMapping("/getSignList")
    @ResponseBody
    public R getSignList(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
                || !params.containsKey("month") || !params.containsKey("month")
                ){
            return R.error("参数异常");
        }
        try{
            List<MemberSignDO> list = memberSignService.getSignList(params);
            //获取签到奖励
            params.put("delFlag", "0");
            params.put("sort", "days");
            params.put("order", "desc");
            List<MemberSignRewardDO> list2 = memberSignRewardService.list(params);
            //获取当前签到规则
            Date date = new Date();
    		SimpleDateFormat sdf1 =new SimpleDateFormat("yyyy-MM-dd" );
    		String str1 = sdf1.format(date);
    		CmsSignDO cmsSignDO = cmsSignService.findByCurrentRule(str1);
    		Map<String, Object> map = new HashMap<>();
    		map.put("signRewardList", list2);
    		map.put("memberSignList", list);
    		map.put("cmsSign", "从"+cmsSignDO.getStartAt()+"到"+cmsSignDO.getEndDate()+",签到时间够"+cmsSignDO.getDays()+"天,赠送参小乙草本洗护旅行装，价值39元。");
            return R.ok().put("data",map);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }
    
    /**
     * 领取签到奖励
     * days  签到完成的日期 比如2020-09-10
     * 
     */
    @PostMapping("/updateSignReward")
    @ResponseBody
    public R updateSignReward(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
                || !params.containsKey("days") || !params.containsKey("days")
                || !params.containsKey("addressId") || !params.containsKey("addressId")
                ){
            return R.error("参数异常");
        }
        try{
            return memberSignRewardService.updateSignReward(params);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 查询个人收货地址
     *//*
    @PostMapping( "/address/list")
    @ResponseBody
    public R addressList(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")){
            return R.error("参数异常");
        }
        try{
            String userId = params.get("userId").toString();
            List<MemberAddressDO> list = memberAddressService.queryByUserId(params);
            return R.ok().put("data", list);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }*/


}
